using UnityEditor;
using UnityEngine;

namespace GameDesigner
{
    [CustomEditor(typeof(AnimationClipReference))]
    public class AnimationClipReferenceEditor : Editor
    {
        private AnimationClipReference animationClipReference;

        private void OnEnable()
        {
            animationClipReference = target as AnimationClipReference;
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            var rect = EditorGUILayout.GetControlRect(GUILayout.Height(100));
            GUI.Box(rect, new GUIContent("将动画剪辑拖入这里!!!"), EditorStyles.selectionRect);
            if (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform)
            {
                if (rect.Contains(Event.current.mousePosition))
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    HandleDragDrop();
                }
            }
        }

        private void HandleDragDrop()
        {
            if (Event.current.type != EventType.DragPerform)
                return;
            foreach (var obj in DragAndDrop.objectReferences)
            {
                // 如果拖入的是单个动画剪辑
                if (obj is AnimationClip clip)
                {
                    AddClipIfNotExists(clip.name);
                    continue;
                }
                // 处理模型文件中的动画
                ProcessModelAnimations(obj);
            }
        }

        private void ProcessModelAnimations(Object obj)
        {
            string assetPath = AssetDatabase.GetAssetPath(obj);
            if (string.IsNullOrEmpty(assetPath))
                return;
            // 尝试获取模型导入器
            var modelImporter = AssetImporter.GetAtPath(assetPath) as ModelImporter;
            if (modelImporter == null)
                return;
            // 获取所有动画剪辑
            var clipAnimations = modelImporter.clipAnimations;
            if (modelImporter.defaultClipAnimations != null && modelImporter.defaultClipAnimations.Length > 0)
                clipAnimations = modelImporter.defaultClipAnimations;
            if (clipAnimations == null || clipAnimations.Length == 0)
                return;
            // 添加所有找到的动画剪辑
            foreach (var clipAnimation in clipAnimations)
                AddClipIfNotExists(clipAnimation.name);
        }

        private void AddClipIfNotExists(string clipName)
        {
            if (string.IsNullOrEmpty(clipName))
                return;
            if (!animationClipReference.ClipNames.Contains(clipName))
                animationClipReference.ClipNames.Add(clipName);
        }
    }
}